/**
 * @Project TMHSC
 * @Author Tran Manh Hung
 * @Email: hungtmit@gmail.com | tmh@xwebgate.com
 * @Copyright © 2011 TMH. All rights reserved
 * @Createdate Jan 31, 2011
 * @Createtime 3:07:59 PM
 */

package com.tmh.study.aASA
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.utils.getTimer;

	/**
	 * Using Vector instead of Array<br />
	 * But it's not increase performent???!
	 */
	public class GridCollision2 extends Sprite
	{
		private const GRID_SIDE:Number = 50;

		private const RADIUS:Number = 25;

		private var _balls:Vector.<DisplayObject>;

		private var _grid:CollisionGrid;

		private var _numBalls:int = 1000;

		public function GridCollision2()
		{
			_grid = new CollisionGrid(stage.stageWidth, stage.stageHeight, GRID_SIDE);
			_grid.drawGrid(graphics);
			makeBalls();
			var startTime:int;
			var elapsed:int;

			// loop 10 time and measure elapsed time
			startTime = getTimer();

			for (var i:int = 0; i < 10; i++)
			{
				_grid.check(_balls);

				var numChecks:uint = _grid.checks.length;

				for (var j:int = 0; j < numChecks; j += 2)
				{
					checkCollision(_grid.checks[j] as Ball, _grid.checks[j + 1] as Ball);
				}
			}

			elapsed = getTimer() - startTime;
			trace("Elapsed: ", elapsed);
		}

		private function makeBalls():void
		{
			_balls = new Vector.<DisplayObject>(_numBalls);

			for (var i:int = 0; i < _numBalls; i++)
			{
				var ball:Ball = new Ball(RADIUS);
				ball.x = Math.random() * stage.stageWidth;
				ball.y = Math.random() * stage.stageHeight;
				ball.vx = Math.random() * 4 - 2;
				ball.vy = Math.random() * 4 - 2;
				addChild(ball);
				_balls[i] = ball;
			}
		}

		private function checkCollision(ballA:Ball, ballB:Ball):void
		{
			var dx:Number = ballB.x - ballA.x;
			var dy:Number = ballB.y - ballA.y;
			var dist:Number = Math.sqrt(dx * dx + dy * dy);

			if (dist < (ballA.radius + ballB.radius))
			{
				ballA.color = 0xcc0000;
				ballB.color = 0x00cc00
			}
		}
	}
}